// RC是配置文件 DEFAULTS是默认配置
import {RC, DEFAULTS} from './constants';
// 格式分析和序列化
import {decode, encode} from 'ini';
// 函数promise化
import {promisify} from 'util';
import fs from 'fs';
import {exit} from 'process';

let exists = promisify(fs.exists);
let readFile = promisify(fs.readFile);
let writeFile = promisify(fs.writeFile);

export const get = async (k) => {
    let has = await exists(RC);
    let opts;
    if (has) {
        opts = readFile(RC, 'utf8');
        opts = decode(opts);
        return opts[k];
    }
    return '';
};

export const set = async (k, v) => {
    let has = exists(RC);
    let opts;
    if (has) {
        opts = await readFile(RC, 'utf8');
        opts = decode(opts);
        Object.assign(opts, {[k]: v});
    } else {
        opts = Object.assign(DEFAULTS, {[k]:v});
    }
    await writeFile(RC, encode(opts), 'utf8');
};
export const remove = async (k) => {
    let has = await exists(RC);
    let opts;
    if (has) {
        opts = await readFile(RC, 'utf8');
        opts = decode(opts);
        delete opts[k];
        await writeFile(RC, encode(opts), 'utf8');
    }
};
export const getAll = async () => {
    let has = await exists(RC);
    let opts;
    if (has) {
        opts = await readFile(RC, 'utf8');
        opts = decode(opts);
        return opts;
    }
    return {};
};